CommonUtils.regNamespace("com.im.unitManage");

com.im.unitManage.invoke = function() {
    var client = new com.im.common.ajax();
    var orgparam = {"forOrgList":"Y","pageInfo":{"pageNumber":1,"pageSize":20}};
    var statusCd;
    var org;//操邹的组织
    var operType;
    var orgcolumns=[[
        {field:'checkRow',title:"选择",width:100,fitColumns:true,checkbox : true  },
        {field:'orgId',title:"序号",width:$(this).width()*0.03,hidden:true,
            formatter: function(value,row,index){
                return  '<input type="radio" name="r1" class="minimal" value='+index+'></input>';
            }},
        {field:'orgName',title:"单位名称",width:$(this).width()*0.15,fitColumns:true},
        {field:'orgCode',title:"单位编码",width:$(this).width()*0.05,fitColumns:true},
        {field:'orgType',title:"单位类型",width:$(this).width()*0.07,fitColumns:true,
            formatter: function(value,row,index){
                var orgTypeName = '未定义';
                $.each(orgTypes,function(i,obj){
                    if(obj.id == value){
                        orgTypeName = obj.text;
                        return false;
                    }
                });
                return orgTypeName ;
            }},
        {field:'orgAddr',title:"单位地址",width:$(this).width()*0.15,fitColumns:true},
        {field:'orgTel',title:"联系方式",width:$(this).width()*0.1,fitColumns:true},
        {field:'orgFax',title:"传真",width:$(this).width()*0.1,fitColumns:true},
        {field:'orgEmail',title:"邮箱",width:$(this).width()*0.1,fitColumns:true},
        {field:'linkMan',title:"联系人",width:$(this).width()*0.06,fitColumns:true},
        {field:'statusName',title:"状态",width:$(this).width()*0.05},
        {field:'operation',title:"操作",width:$(this).width()*0.06,fitColumns:true,
            formatter: function(value,row,index){
                return  '<a href="javascript:;" onclick="com.im.unitManage.invoke.modifyOrg(\''+index+'\',\'query\')" title="详情"><i class="fa fa-file-text-o"></i></a>'+
                        '<a href="javascript:;" onclick="com.im.unitManage.invoke.modifyOrg(\''+index+'\',\'modify\')" title="修改"><i class="fa fa-edit"></i></a>'+
                        '<!--<a href="javascript:;" onclick="com.im.unitManage.invoke.modifyOrg(\''+index+'\',\'del\')" title="删除"><i class="fa fa-trash"></i></a>-->';
            }}
    ]];
	function _init() {

        //初始化组织树
        $("#jobTree").unitCommpent({
            elmId : "jobTree",//组织树显示的<ul>元素id
            elmIdOut : null,//组织树单击之后回填的文本框（input）
            hasOrgType : true,//组织树是否先展示组织类型
            treeOnClick: function (orgId, orgName) {//组织树单击之后回调函数
                orgparam.orgId = orgId;
                orgparam.forOrgList = 'Y';
                orgparam.orgType = '';
                _showOrgList(1);
            }
        });
       //初始化组织类型
        _initOrgType();

        //查询
        $("#orgSearchBtn").click(function(){
            orgparam.forOrgList = 'Y';
            orgparam.orgType = $("#selectOrgType").val();
            orgparam.orgName = $("#orgNameTxt").val();
            orgparam.orgId = '';

            _showOrgList(1);
        });

        //新增
        $("#orgAddBtn").click(function(){
            operType =  "add";
            $("#modalTitle").html("增加单位");
            $("#AddEditModal").modal("show");
            _showOrgInfo(null);
        });

        //直接调用show看动态加载模态框不能显示出来
        $('#AddEditModal').on('shown.bs.modal', function () {
            //展示组织信息
        });

        $("#saveBtn").click(function(){
            _saveOrUpdate();
        });
        //初始化加载
        _showOrgList(1);

        //下拉框值改变
        $("#selectOrgType").change(function () {
            orgparam.orgId = '';
            orgparam.forOrgList = 'Y';
            orgparam.orgType = $("#selectOrgType").val();
            _showOrgList(1);
        });

        //
        $("#batchDelBtn").click(function () {
            _batchUpadateOrg("batchdel");
        });

        //用户状态
        $('#statusCdTxt').switchbutton({
            checked: true,
            onChange: function(checked){
                if (checked == true){
                    statusCd = '10';
                    orgparam.statusCd = statusCd;
                    _showOrgList(1)
                }
                if (checked == false) {
                    statusCd = '20';
                    orgparam.statusCd = statusCd;
                    _showOrgList(1);
                }}
        });
        //初始化表单验证
        _initFormValid();

        //校验单位名称
        $("#orgNameInput").blur(function(){
            _checkOrgName();
        });

    };

	function _checkOrgName(){
        var orgName = $("#orgNameInput").val();
        if(orgName == undefined || orgName == ''){
            return;
        }
        var param = {};
        param.orgName = orgName;
        var result = client.callAsJson("userService/queryOrgarizationDetail", param);
        if(result.success){
            if(result.result.orgName != undefined && result.result.orgName != null){
                toastr.warning("您输入的单位名称已经存在，请重新输入！");
                $("#orgNameInput").val('');
            }
        }else{
            toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
        }
    }

    function _initFormValid(){
        $("#unitForm").bootstrapValidator({
            live: 'enabled',
            excluded: [':hidden'],
            feedbackIcons: {valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-loadData'},
            fields: {
                orgNameInput : {validators: {notEmpty: {message: "请填写单位名称."}}}
                ,orgTypeSel : {validators: {notEmpty: {message: "请选择单位类型."}}}
                //,orgAddrInput : {validators: {notEmpty: {message: "请填写单位地址."}}}
                //,orgTelInput : {validators: {notEmpty: {message: "请填写单位电话."}}}
                //,linkManInput : {validators: {notEmpty: {message: "请填写联系人."}}}
                ,linkManTelInput : {validators:
                        {//notEmpty: {message: "请填写联系人手机."},
                        regexp: {
                            regexp: /^((1[3,5,8][0-9])|(14[5,7])|(17[0,6,7,8])|(19[7]))\d{8}$/,
                            message: '手机号码格式有误.'
                        }}}
                //,linkManPhoneInput : {validators: {notEmpty: {message: "请填写联系人电话."}}}
                ,linkManEmailInput : {validators: {
                    //notEmpty: {message: "请填写邮箱地址."},
                        emailAddress: {message: "邮箱格式有误."}}}
            }
        });
    };
	function _modifyOrg(idx,type){
	    //先清除表单校验结果
        $('#unitForm').data('bootstrapValidator',null);
        _initFormValid();

        org = $('#orgListTb').datagrid('getData').rows[idx];
        if(type == 'modify'){
            operType =  "modify";
            $("#modalTitle").html("修改单位");
            $("#AddEditModal").modal("show");
            _showOrgInfo(org);
        }
        if(type == 'del'){
            operType =  "del";
            $("#modalTitle").html("删除单位");
            $("#AddEditModal").modal("show");
            _showOrgInfo(org);
        }
        if(type == 'query'){
            operType =  "query";
            $("#modalTitle").html("查看单位");
            $("#AddEditModal").modal("show");
            _showOrgInfo(org);
        }

    };
	function _saveOrUpdate(){

        $("#unitForm").bootstrapValidator('validate');//提交验证
        if (!$("#unitForm").data('bootstrapValidator').isValid()) {//获取验证结果，如果成功，执行下面代码
            return;
        }
	    if(operType == 'query'){
            $("#AddEditModal").modal("hide");
            return;
        }
       var orgName =  $("#orgNameInput").val();
        if(orgName == undefined || orgName == ''){
            toastr.warning("请填写单位名称！！");
            return;
        }
       var orgType =  $("#orgTypeSel").val();
        if(orgType == undefined || orgType == ''){
            toastr.warning("请选择单位类型！！");
            return;
        }
       var orgAddr = $("#orgAddrInput").val();
        // if(orgAddr == undefined || orgAddr == ''){
        //     toastr.warning("请填写单位地址！！");
        //     return;
        // }
       var orgTel = $("#orgTelInput").val();
        // if(orgTel == undefined || orgTel == ''){
        //     toastr.warning("请单位联系方式！！");
        //     return;
        // }
       var orgFax =  $("#orgFaxInput").val();
       var orgEmail =  $("#orgEmailInput").val();

       var linkMan = $("#linkManInput").val();
        // if(linkMan == undefined || linkMan == ''){
        //     toastr.warning("请填写单位联系人！！");
        //     return;
        // }
       var linkManTel =  $("#linkManTelInput").val();
        // if(linkManTel == undefined || linkManTel == ''){
        //     toastr.warning("请填写单位联系人电话！！");
        //     return;
        // }
       var linkManPhone = $("#linkManPhoneInput").val();
        // if(linkManPhone == undefined || linkManPhone == ''){
        //     toastr.warning("请填写单位联系人手机号码！！");
        //     return;
        // }
       var linkManEmail = $("#linkManEmailInput").val();
        // if(linkManEmail == undefined || linkManEmail == ''){
        //     toastr.warning("请填写联系人邮箱！！");
        //     return;
        // }

        var uparam = {};
        var orgparam = {};
        orgparam.orgName = orgName;
        orgparam.orgType = orgType;
        orgparam.orgAddr = orgAddr;
        orgparam.orgTel = orgTel;
        orgparam.orgEmail = orgEmail;
        orgparam.orgFax = orgFax;
        orgparam.linkMan = linkMan;
        orgparam.linkManTel = linkManTel;
        orgparam.linkManPhone = linkManPhone;
        orgparam.linkManEmail = linkManEmail;
        orgparam.orgName = orgName;
        orgparam.operType = operType;
        if(operType != 'add'){
            orgparam.orgId = org.orgId;
        }
        uparam.org = orgparam;

        var result = client.callAsJson("userService/saveOrUpdateOrg", uparam);
        if(result.success){
            $("#AddEditModal").modal("hide");
            _showOrgList(1);
            if(operType  == 'add' || operType  == 'del'){
                //重新加载
                $("#jobTree").unitCommpent({
                    elmId : "jobTree",//组织树显示的<ul>元素id
                    elmIdOut : null,//组织树单击之后回填的文本框（input）
                    hasOrgType : true,//组织树是否先展示组织类型
                    treeOnClick: function (orgId, orgName) {//组织树单击之后回调函数
                        orgparam.orgId = orgId;
                        orgparam.forOrgList = 'Y';
                        orgparam.orgType = '';
                        _showOrgList(1);
                    }
                });
            }
            toastr.info("操作成功！");
        }else{
            toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
        }
    }
    function _showOrgInfo(org){
	    if(operType == 'add'){
            $("#orgNameInput").val('');
            $("#orgTypeSel").val('');
            $("#orgAddrInput").val('');
            $("#orgTelInput").val('');
            $("#orgFaxInput").val('');
            $("#orgEmailInput").val('');
            $("#linkManInput").val('');
            $("#linkManTelInput").val('');
            $("#linkManPhoneInput").val('');
            $("#linkManEmailInput").val('');
        }else{
            $("#orgNameInput").val(org.orgName);
            $("#orgTypeSel").val(org.orgType).trigger("change");
            $("#orgAddrInput").val(org.orgAddr);
            $("#orgTelInput").val(org.orgTel);
            $("#orgFaxInput").val(org.orgFax);
            $("#orgEmailInput").val(org.orgEmail);
            $("#linkManInput").val(org.linkMan);
            $("#linkManTelInput").val(org.linkManTel);
            $("#linkManPhoneInput").val(org.linkManPhone);
            $("#linkManEmailInput").val(org.linkManEmail);
        }

        if(operType == 'query' || operType == 'del'){
            $("#orgNameInput").attr("disabled","disabled");
            $("#orgTypeSel").attr("disabled","disabled");
            $("#orgAddrInput").attr("disabled","disabled");
            $("#orgTelInput").attr("disabled","disabled");
            $("#orgFaxInput").attr("disabled","disabled");
            $("#orgEmailInput").attr("disabled","disabled");
            $("#linkManInput").attr("disabled","disabled");
            $("#linkManTelInput").attr("disabled","disabled");
            $("#linkManPhoneInput").attr("disabled","disabled");
            $("#linkManEmailInput").attr("disabled","disabled");
        }else{
            $("#orgNameInput").removeAttr("disabled");
            $("#orgTypeSel").removeAttr("disabled");
            $("#orgAddrInput").removeAttr("disabled");
            $("#orgTelInput").removeAttr("disabled");
            $("#orgFaxInput").removeAttr("disabled");
            $("#orgEmailInput").removeAttr("disabled");
            $("#linkManInput").removeAttr("disabled");
            $("#linkManTelInput").removeAttr("disabled");
            $("#linkManPhoneInput").removeAttr("disabled");
            $("#linkManEmailInput").removeAttr("disabled");
        }
        if(operType == 'query'){
	        $("#saveBtn").hide();
        }else{
            $("#saveBtn").show();
        }
    }
    function _initOrgType(){
        var result = client.callAsJson("userService/queryOrgarizationsByCond", { "hasOrgType":'Y'});
        if(result.success){
            orgTypes = result.result;
            $("#selectOrgType").append("<option value=''>全部</option>");
            $("#orgTypeSel").append("<option value=''>请选择</option>");
            $.each(orgTypes,function(i,obj){
                $("#selectOrgType").append("<option value='"+obj.id+"'>"+obj.text+"</option>"); ;
                $("#orgTypeSel").append("<option value='"+obj.id+"'>"+obj.text+"</option>"); ;
            });
        }else{
            toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
        }
        $('.select2').select2();
    };
    function _showOrgList(pageNum){
        $("#orgListTb").empty();
        var pageInfo = {};
        pageInfo.pageNumber = pageNum;
        var result = client.callAsJson("userService/queryOrgarizationsByCondPage", orgparam);
        if (result.success) {
            if(result.result != null){
                $("#orgListTb").datagrid({
            	    nowrap:false,
            	    fitColumns:true,
                    columns : orgcolumns,
                    data : result.result
                });

                //页码
                $("#page").pagination({
                    total : result.result.total,
                    pageSize : result.result.pageSize,
                    pageNumber : result.result.pageNumber,
                    pageList : [20 , 40],
                    beforePageText:  '第' ,
                    afterPageText: '页 共'+result.result.totalPages+'页',
                    displayMsg: '共 '+result.result.total+'条记录',
                    onSelectPage: function (pageNumber, pageSize) {
                        orgparam.pageInfo.pageNumber = pageNumber;
                        orgparam.pageInfo.pageSize = pageSize;
                        _showOrgList(pageNumber);
                    }
                });
            }
        } else {
            toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
        }

    };
    function _batchUpadateOrg(type){

        var nowlist = $("#orgListTb").datagrid('getChecked');
        if(nowlist != undefined && nowlist.length > 0){
            var msgStr = "确认批量失效"+nowlist.length+"个单位么？";
            if(statusCd == '20'){
                type = "batcheff";
                var msgStr = "确认批量生效"+nowlist.length+"个单位么？";
            }
            com.im.common.confirm(msgStr,{},function(){
                var orgList = [];
                $.each(nowlist,function (i,obj) {
                    orgList.push(obj.orgId);
                });
                var result = client.callAsJson("userService/saveOrUpdateOrg", {orgList : orgList ,batchOperType : type});
                if(result.success){
                    toastr.info("操作成功！");
                    _showOrgList(1);
                }else{
                    toastr.error("服务器忙，请稍后再试！"+result.resultMsg);
                }
            });
        }
    }

    return {
		init : _init,
        modifyOrg : _modifyOrg
	}
}();

$(function() {
	com.im.unitManage.invoke.init();
});